<template>
  <div class="game-canvas-container">
    <div class="canvas-toolbar">
      <div class="tool-group">
        <button 
          :class="['tool-btn', { active: currentTool === 'brush' }]"
          @click="setTool('brush')"
        >
          🖌️ 画笔
        </button>
        <button 
          :class="['tool-btn', { active: currentTool === 'eraser' }]"
          @click="setTool('eraser')"
        >
          🧽 橡皮擦
        </button>
      </div>
      <div class="brush-size-group">
        <label>画笔大小:</label>
        <input 
          type="range" 
          min="5" 
          max="30" 
          v-model="brushSize" 
          class="brush-slider"
        />
        <span>{{ brushSize }}px</span>
      </div>
    </div>
    
    <div class="canvas-wrapper">
      <canvas
        ref="canvas"
        :width="canvasWidth"
        :height="canvasHeight"
        class="game-canvas"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
      ></canvas>
      
      <div class="canvas-overlay" v-if="gameStatus?.toLowerCase() === 'waiting'">
        <div class="waiting-message">
          <h3>等待游戏开始...</h3>
          <p>玩家数量: {{ playerCount }}/{{ maxPlayers }}</p>
        </div>
      </div>
      
      <div class="canvas-overlay" v-if="gameStatus?.toLowerCase() === 'paused'">
        <div class="paused-message">
          <h3>游戏暂停</h3>
          <p>等待房主恢复游戏...</p>
        </div>
      </div>
      
             <div class="canvas-overlay" v-if="gameStatus?.toLowerCase() === 'finished'">
        <div class="game-result">
          <h3>游戏结束!</h3>
          <div class="winner-info">
            <p>获胜者: {{ winner?.nickname }}</p>
            <p>占领面积: {{ winner?.area }} 像素</p>
          </div>
          <div class="final-scores">
            <h4>最终排名:</h4>
            <div v-for="(player, index) in sortedPlayers" :key="player.id" class="player-score">
              <span class="rank">{{ index + 1 }}</span>
              <span class="nickname">{{ player.nickname }}</span>
              <span class="area">{{ player.area || 0 }} 像素</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="canvas-info">
      <div class="coordinates">
        坐标: ({{ mouseX }}, {{ mouseY }})
      </div>
      <div class="connection-status" :class="connectionStatus">
        {{ connectionStatusText }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
import { useGameStore } from '../stores/game'

const props = defineProps({
  canvasWidth: {
    type: Number,
    default: 800
  },
  canvasHeight: {
    type: Number,
    default: 600
  },
  gameStatus: {
    type: String,
    default: 'waiting' // waiting, playing, paused, finished
  },
  playerCount: {
    type: Number,
    default: 0
  },
  maxPlayers: {
    type: Number,
    default: 6
  },
  winner: {
    type: Object,
    default: null
  },
  remainingTime: {
    type: Number,
    default: 0
  },
  sortedPlayers: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['paint-action', 'tool-changed'])

const gameStore = useGameStore()

// Canvas相关
const canvas = ref(null)
const ctx = ref(null)
const isDrawing = ref(false)
const lastX = ref(0)
const lastY = ref(0)

// 工具设置
const currentTool = ref('brush')
const brushSize = ref(10)

// 鼠标位置
const mouseX = ref(0)
const mouseY = ref(0)

// 连接状态
const connectionStatus = ref('connected')
const connectionStatusText = computed(() => {
  switch (connectionStatus.value) {
    case 'connected': return '已连接'
    case 'connecting': return '连接中...'
    case 'disconnected': return '连接断开'
    default: return '未知状态'
  }
})

// 颜色区域统计
const colorAreas = ref(new Map())
const playerColors = ref(new Map())

// 计算面积变化 - 基于像素数量
const calculateAreaChange = (x1, y1, x2, y2, brushSize) => {
  // 计算画笔覆盖的像素数量
  const radius = Math.floor(brushSize / 2)
  const distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2))
  
  // 估算覆盖的像素数量
  const pixelsPerUnit = Math.max(1, Math.floor(distance / brushSize))
  const area = Math.PI * radius * radius * pixelsPerUnit
  
  return Math.round(area)
}

// 时间格式化
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 计算颜色区域面积 - 更精确的方法
const calculateColorArea = (color) => {
  if (!ctx.value) return 0
  
  const imageData = ctx.value.getImageData(0, 0, props.canvasWidth, props.canvasHeight)
  const data = imageData.data
  let pixelCount = 0
  
  // 将颜色转换为RGB值进行比较
  const targetColor = hexToRgb(color)
  
  for (let i = 0; i < data.length; i += 4) {
    const r = data[i]
    const g = data[i + 1]
    const b = data[i + 2]
    const a = data[i + 3] // 透明度
    
    // 只计算不透明的像素
    if (a > 128) {
      // 允许一定的颜色容差，但更严格
      if (Math.abs(r - targetColor.r) < 5 && 
          Math.abs(g - targetColor.g) < 5 && 
          Math.abs(b - targetColor.b) < 5) {
      pixelCount++
      }
    }
  }
  
  return pixelCount
}

// 十六进制颜色转RGB
const hexToRgb = (hex) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : { r: 0, g: 0, b: 0 }
}

// 更新颜色区域统计
const updateColorAreas = () => {
  if (!ctx.value) return
  
  const newColorAreas = new Map()
  
  // 计算每个玩家的颜色区域
  for (const [playerId, color] of playerColors.value) {
    const area = calculateColorArea(color)
    newColorAreas.set(playerId, area)
    
    // 直接更新玩家面积
    gameStore.updatePlayerArea(playerId, area)
  }
  
  colorAreas.value = newColorAreas
  
  // 发送面积更新到游戏状态
  gameStore.updatePlayerAreas(newColorAreas)
  
  console.log('Updated color areas:', Object.fromEntries(newColorAreas))
}

// 初始化Canvas
const initCanvas = () => {
  if (!canvas.value) {
    console.log('Canvas element not found')
    return
  }
  
  ctx.value = canvas.value.getContext('2d')
  console.log('Canvas context initialized:', ctx.value)
  
  // 设置画布背景
  ctx.value.fillStyle = '#f0f0f0'
  ctx.value.fillRect(0, 0, props.canvasWidth, props.canvasHeight)
  
  // 设置默认画笔样式
  ctx.value.lineCap = 'round'
  ctx.value.lineJoin = 'round'
  ctx.value.strokeStyle = gameStore.currentPlayer?.color || '#000000'
  ctx.value.lineWidth = brushSize.value
  
  console.log('Canvas initialized with size:', props.canvasWidth, 'x', props.canvasHeight)
}

// 设置工具
const setTool = (tool) => {
  currentTool.value = tool
  emit('tool-changed', tool)
  
  if (ctx.value) {
    if (tool === 'eraser') {
      ctx.value.globalCompositeOperation = 'destination-out'
    } else {
      ctx.value.globalCompositeOperation = 'source-over'
    }
  }
}

// 获取鼠标位置
const getMousePos = (event) => {
  const rect = canvas.value.getBoundingClientRect()
  const scaleX = canvas.value.width / rect.width
  const scaleY = canvas.value.height / rect.height
  
  return {
    x: (event.clientX - rect.left) * scaleX,
    y: (event.clientY - rect.top) * scaleY
  }
}

// 开始绘制
const startDrawing = (event) => {
  console.log('Start drawing, game status:', props.gameStatus)
  // 统一转换为小写进行比较
  const status = props.gameStatus?.toLowerCase()
  if (status !== 'playing') {
    console.log('Game not in playing state, cannot draw')
    return
  }
  
  isDrawing.value = true
  const pos = getMousePos(event)
  lastX.value = pos.x
  lastY.value = pos.y
  
  console.log('Drawing started at:', pos.x, pos.y)
  
  // 设置画笔颜色
  if (ctx.value) {
    ctx.value.strokeStyle = gameStore.currentPlayer?.color || '#000000'
    ctx.value.lineWidth = brushSize.value
    console.log('Set stroke style:', ctx.value.strokeStyle, 'line width:', ctx.value.lineWidth)
  } else {
    console.log('Canvas context not available')
  }
}

// 绘制
const draw = (event) => {
  if (!isDrawing.value) {
    console.log('Cannot draw - isDrawing:', isDrawing.value, 'gameStatus:', props.gameStatus)
    return
  }
  
  // 统一转换为小写进行比较
  const status = props.gameStatus?.toLowerCase()
  if (status !== 'playing') {
    console.log('Cannot draw - game status not allowed:', props.gameStatus)
    return
  }
  
  const pos = getMousePos(event)
  mouseX.value = Math.round(pos.x)
  mouseY.value = Math.round(pos.y)
  
  console.log('Drawing at:', pos.x, pos.y)
  
  if (ctx.value) {
    ctx.value.beginPath()
    ctx.value.moveTo(lastX.value, lastY.value)
    ctx.value.lineTo(pos.x, pos.y)
    ctx.value.stroke()
    
    console.log('Drew line from', lastX.value, lastY.value, 'to', pos.x, pos.y)
    
    // 计算面积变化
    const areaChange = calculateAreaChange(lastX.value, lastY.value, pos.x, pos.y, brushSize.value)
    
    // 发送绘制动作到服务器
    emit('paint-action', {
      x: Math.round(pos.x),
      y: Math.round(pos.y),
      brushSize: brushSize.value,
      tool: currentTool.value,
      color: gameStore.currentPlayer?.color,
      areaChange: areaChange
    })
    
    // 延迟更新面积统计，确保绘制完成
    setTimeout(() => {
      updateColorAreas()
    }, 50)
  } else {
    console.log('Canvas context not available for drawing')
  }
  
  lastX.value = pos.x
  lastY.value = pos.y
}

// 停止绘制
const stopDrawing = () => {
  isDrawing.value = false
}

// 触摸事件处理
const handleTouchStart = (event) => {
  event.preventDefault()
  if (event.touches.length === 1) {
    const touch = event.touches[0]
    const mouseEvent = new MouseEvent('mousedown', {
      clientX: touch.clientX,
      clientY: touch.clientY
    })
    startDrawing(mouseEvent)
  }
}

const handleTouchMove = (event) => {
  event.preventDefault()
  if (event.touches.length === 1) {
    const touch = event.touches[0]
    const mouseEvent = new MouseEvent('mousemove', {
      clientX: touch.clientX,
      clientY: touch.clientY
    })
    draw(mouseEvent)
  }
}

const handleTouchEnd = (event) => {
  event.preventDefault()
  stopDrawing()
}

// 接收远程绘制动作
const receivePaintAction = (paintData) => {
  if (!ctx.value || props.gameStatus?.toLowerCase() !== 'playing') return
  
  // 临时保存当前设置
  const originalStrokeStyle = ctx.value.strokeStyle
  const originalLineWidth = ctx.value.lineWidth
  const originalCompositeOperation = ctx.value.globalCompositeOperation
  
  // 设置远程绘制样式
  ctx.value.strokeStyle = paintData.color
  ctx.value.lineWidth = paintData.brushSize
  
  if (paintData.tool === 'eraser') {
    ctx.value.globalCompositeOperation = 'destination-out'
  } else {
    ctx.value.globalCompositeOperation = 'source-over'
  }
  
  // 绘制
  ctx.value.beginPath()
  ctx.value.moveTo(paintData.x - 1, paintData.y - 1)
  ctx.value.lineTo(paintData.x, paintData.y)
  ctx.value.stroke()
  
  // 恢复原始设置
  ctx.value.strokeStyle = originalStrokeStyle
  ctx.value.lineWidth = originalLineWidth
  ctx.value.globalCompositeOperation = originalCompositeOperation
  
  // 延迟更新颜色区域统计，确保绘制完成
  setTimeout(() => {
    updateColorAreas()
  }, 50)
}

// 清空画布
const clearCanvas = () => {
  if (ctx.value) {
    ctx.value.fillStyle = '#f0f0f0'
    ctx.value.fillRect(0, 0, props.canvasWidth, props.canvasHeight)
  }
}

// 暴露方法给父组件
defineExpose({
  receivePaintAction,
  clearCanvas,
  updateColorAreas,
  getColorAreas: () => colorAreas.value,
  setPlayerColors: (colors) => {
    playerColors.value = new Map(Object.entries(colors))
    console.log('Player colors set:', colors)
  }
})

// 监听画布尺寸变化
watch(() => [props.canvasWidth, props.canvasHeight], () => {
  nextTick(() => {
    initCanvas()
  })
})

// 监听游戏状态变化
watch(() => props.gameStatus, (newStatus) => {
  if (newStatus?.toLowerCase() === 'playing') {
    // 游戏开始时清空画布
    clearCanvas()
    // 初始化玩家颜色映射
    if (gameStore.players.length > 0) {
      const playerColorsMap = {}
      gameStore.players.forEach(player => {
        playerColorsMap[player.id] = player.color
      })
      playerColors.value = new Map(Object.entries(playerColorsMap))
    }
  }
})

onMounted(() => {
  initCanvas()
  
  // 监听玩家颜色更新事件
  window.addEventListener('updatePlayerColors', (event) => {
    if (event.detail) {
      playerColors.value = new Map(Object.entries(event.detail))
      console.log('Player colors updated:', event.detail)
    }
  })
  
  // 监听远程绘制事件
  window.addEventListener('remotePaintAction', (event) => {
    if (event.detail) {
      receivePaintAction(event.detail)
    }
  })
  
  // 移除测试绘制，让Canvas保持干净
  // setTimeout(() => {
  //   if (ctx.value) {
  //     console.log('Testing canvas drawing...')
  //     ctx.value.fillStyle = 'red'
  //     ctx.value.fillRect(10, 10, 50, 50)
  //     console.log('Test rectangle drawn')
  //   }
  // }, 1000)
})

onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener('updatePlayerColors', (event) => {
    if (event.detail) {
      playerColors.value = new Map(Object.entries(event.detail))
    }
  })
  
  window.removeEventListener('remotePaintAction', (event) => {
    if (event.detail) {
      receivePaintAction(event.detail)
    }
  })
})
</script>

<style scoped>
.game-canvas-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-width: 100%;
}

.canvas-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.tool-group {
  display: flex;
  gap: 8px;
}

.tool-btn {
  padding: 8px 16px;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
}

.tool-btn:hover {
  background: #e9ecef;
}

.tool-btn.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.brush-size-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.brush-slider {
  width: 100px;
}

.canvas-wrapper {
  position: relative;
  display: flex;
  justify-content: center;
  border: 2px solid #dee2e6;
  border-radius: 8px;
  overflow: hidden;
}

.game-canvas {
  cursor: crosshair;
  background: #f0f0f0;
  touch-action: none; /* 防止移动端滚动 */
  border: 1px solid #ccc; /* 添加边框以便看到Canvas */
  display: block; /* 确保Canvas正确显示 */
}

.canvas-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-align: center;
}

.waiting-message h3,
.game-result h3,
.paused-message h3 {
  margin: 0 0 10px 0;
  font-size: 24px;
}

.game-result {
  max-width: 400px;
  padding: 2rem;
}

.winner-info {
  margin-bottom: 1.5rem;
  padding: 1rem;
  background: rgba(255,255,255,0.1);
  border-radius: 8px;
}

.final-scores {
  text-align: left;
}

.final-scores h4 {
  margin: 0 0 1rem 0;
  text-align: center;
}

.player-score {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem;
  margin-bottom: 0.5rem;
  background: rgba(255,255,255,0.1);
  border-radius: 4px;
}

.rank {
  font-weight: bold;
  color: #ffd700;
  min-width: 30px;
}

.nickname {
  flex: 1;
  margin: 0 1rem;
}

.area {
  color: #90ee90;
  font-weight: bold;
}

.game-timer {
  font-weight: bold;
  color: #007bff;
  font-size: 1.1rem;
}

.canvas-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  font-size: 14px;
  color: #6c757d;
}

.connection-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.connection-status.connected {
  background: #d4edda;
  color: #155724;
}

.connection-status.connecting {
  background: #fff3cd;
  color: #856404;
}

.connection-status.disconnected {
  background: #f8d7da;
  color: #721c24;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .canvas-toolbar {
    flex-direction: column;
    gap: 10px;
  }
  
  .tool-group {
    width: 100%;
    justify-content: center;
  }
  
  .brush-size-group {
    width: 100%;
    justify-content: center;
  }
  
  .game-canvas {
    max-width: 100%;
    height: auto;
  }
}
</style>
